package com.caimiao.miao.library.utils.sys;

import android.content.Context;
import android.text.TextUtils;

import com.caimiao.miao.MiaoApplication;
import com.caimiao.miao.library.utils.AES2Util;
import com.caimiao.miao.library.utils.AESUtil;
import com.caimiao.miao.library.utils.Base64Util;
import com.caimiao.miao.library.utils.storage.FileUtil;

import java.io.File;

public class DeviceUtil {
    private static final String CACHE_IMAGE_DIR = ".AndroidOS/.System/.File/";
    private static final String DEVICES_FILE_NAME = ".DEV";
    private static String mDeviceId;

    /**
     * 解析设备唯一标识符
     *
     * @return
     */
    private static String decryptDeviceId(Context context) {
        //读取保存的在sd卡中的唯一标识符
        String deviceId = FileUtil.read(CACHE_IMAGE_DIR, DEVICES_FILE_NAME);
        if (!TextUtils.isEmpty(deviceId)) {
            try {
                byte[] decode = Base64Util.decode(deviceId.getBytes());
                byte[] secret = new byte[32];
                byte[] source = new byte[decode.length - secret.length];
                System.arraycopy(decode, 0, secret, 0, secret.length);
                System.arraycopy(decode, secret.length, source, 0, source.length);
                byte[] ret = AESUtil.decrypt(source, secret);
                deviceId = new String(Base64Util.decode(ret));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (MiaoApplication.isDebug) {
            deviceId = createDeviceId(context);
        }
        return deviceId;
    }

    /**
     * 获取设备唯一标识符
     *
     * @return
     */
    public static String getDeviceId(Context context) {
        if (mDeviceId == null) {
            synchronized (DeviceUtil.class) {
                if (mDeviceId == null) {
                    mDeviceId = decryptDeviceId(context);
                }
            }
        }
        return mDeviceId;
    }

    public static String createDeviceId(Context context) {
        final String dir = ".AndroidOS/.System/.File/";
        final String name = ".DEV";
        StringBuilder sb = new StringBuilder();
        sb.append(String.valueOf(System.currentTimeMillis()));
        sb.append(MacUtil.getLocalMac(context).replace(":", ""));
        String deviceId = sb.toString();

        File file = FileUtil.save(encode(deviceId), dir, name);
        if (file.canWrite()) {
            if (!file.setReadOnly())
                file.setReadable(true, false);
        }
        return deviceId;
    }

    private static String encode(String value) {
        String encode = Base64Util.encode(value.getBytes());
        return Base64Util.encode(AES2Util.encryptByAES(encode.getBytes()));
    }
}
